package org.jxf.gps.jt808.nettysample.test;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;
import org.jfk.core.utils.ByteUtils;
import org.jxf.gps.jt808.message.MessageParser;

import com.csvreader.CsvReader;

public class UDPClient {
	private static Logger logger = Logger.getLogger(UDPClient.class);
	
	private ConnectionlessBootstrap  bootstrap;
    private Channel channel;
    private InetSocketAddress isa;
    public void start(){
        //init the bootstrap
        bootstrap=new ConnectionlessBootstrap(new NioDatagramChannelFactory());
        bootstrap.setPipelineFactory(new UDPClientChannelPipelineFactory());
        bootstrap.setOption("localAddress", new InetSocketAddress(10001));
        channel=bootstrap.bind();
        
        isa = new InetSocketAddress("127.0.0.1",9090);
    }
    
    public void send() throws Exception{
        if(bootstrap==null){
            this.start();
        }
        
		CsvReader r = new CsvReader(
				"C:\\Users\\Administrator\\Desktop\\trace\\车辆鄂Q07777在20150119000000至20150119082249时段轨迹导出.csv",
				',', Charset.forName("GBK"));
		r.readHeaders();
		// 逐条读取记录，直至读完
		int i = 0;
		while (r.readRecord()) {
			String ss = Client.getData(r,"1889999");
			sendMsg(channel,ss);
			Thread.sleep(1);
			i++;
		}
		System.out.println(i);
		r.close();
    }
    
	public void sendMsg(Channel channel ,String hexString) throws Exception{
		byte[] msgBuff = ByteUtils.hexStringToBytes(hexString);
		byte[] head_body = new byte[msgBuff.length - 3];
		System.arraycopy(msgBuff, 1, head_body, 0, head_body.length);
		byte crc = ByteUtils.genCRC16(head_body);
		msgBuff[msgBuff.length - 2] = crc;
		byte[] newBuff = MessageParser.convert7E7D(msgBuff);
		ChannelBuffer buf = ChannelBuffers.buffer(newBuff.length);
		buf.writeBytes(newBuff);
		//logger.info(ByteUtils.byteToHexString(newBuff));
		channel.write(buf,isa);
	}    
    
    public static void main(String[] args)  {
        
        
        UDPClient uClient=new UDPClient();
        try {
			uClient.send();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }
}
